from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.response import Response

from goods.models import SKUImage,SKU
from celery_tasks.static_files.tasks import get_detail_html


class ImageSerializer(serializers.ModelSerializer):
    sku = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = SKUImage
        fields = '__all__'

    def create(self,  *args, **kwargs):
        sku_id = self.context['request'].data.get('sku')[0]
        file = self.context['request'].FILES.get('image')
        client = Fdfs_client(settings.FASTDFS_PATH)
        res = client.upload_appender_by_buffer(file.read())
        image_path = res['Remote file_id']
        if res['Status']!='Upload successed.':
            raise serializers.ValidationError({'error':"上传图片失败"})
        image = SKUImage.objects.create(sku_id = sku_id,image = image_path )
        get_detail_html.delay(image.sku.id)
        return image

    def update(self, instance, validated_data):
        sku_id = self.context['request'].data.get('sku')[0]
        file = self.context['request'].FILES.get('image')
        client = Fdfs_client(settings.FASTDFS_PATH)
        res = client.upload_appender_by_buffer(file.read())
        image_path = res['Remote file_id']
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError({'error': "上传图片失败"})
        instance.image = res['Remote file_id']
        instance.save()
        get_detail_html.delay(instance.sku.id)
        return instance

class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = '__all__'